#include <cerrno>
#include <cstdio>
#include <iostream>
#include <time.h>
#include <fstream>
#include <math.h>
#include "DNA_vec_types.h"

using namespace std;

struct line
{
	float a,b,c,m;
	vec2f dir;
};

struct segm 
{
	vec2f p1,p2;
	line myLine;
} ;


#define MIN_DIST 100
#define MAX_DIST 400

#define IMG_WIDTH 800
#define IMG_HEIGHT 600

#define MAX_DIST_VP 2000

#define NUM_LINES 20


#define ERROR 0.01
#define PI 3.14159265358979323

vec2f vp;//Vanishing point
segm segments[NUM_LINES];
line lines[NUM_LINES];


void calculateIntersection(segm s1, segm s2, vec2f *res)
{
	res->x= (s2.myLine.c - s1.myLine.c) / (s1.myLine.m - s2.myLine.m );
	res->y= s1.myLine.m*res->x + s1.myLine.c;
}


int main()
{
	int i;
	//iniciamos el random
	srand(time(NULL));
	ofstream myfile ("/tmp/test_001.data");
	
	vp.x= IMG_WIDTH + rand() % MAX_DIST_VP;
	vp.y= rand() % MAX_DIST_VP/2;
	myfile << "#Vanishing point\n";
	myfile << vp.x << "\t" << vp.y << "\n\n\n";
	myfile << "#Points\n";
	for(i=0; i<NUM_LINES; i++){
		vec2f p1, p2, dir;
		float m;
		float alpha;
		
		p1.x= rand() % IMG_WIDTH;
		p1.y= rand() % IMG_HEIGHT;

		dir.x= vp.x - p1.x;
		dir.y= vp.y - p1.y;
		
		m= dir.y / dir.x;

		alpha= atan(m);
		
		alpha+=  ((float)(rand() / RAND_MAX)-0.5)*PI*ERROR;
		m= tan( alpha );
		
		float d=sqrt( (m*m + 1) );
		dir.x=1/d;
		dir.y=m/d;
		
		float newd= (float)(rand() / RAND_MAX)*MAX_DIST + MIN_DIST;
		vec2f dp;
		dp.x=newd*dir.x;
		dp.y=newd*dir.y;

		p2.x= dp.x + p1.x;
		p2.y= dp.y + p1.y;

		segments[i].p1=p1;
		segments[i].p2=p2;
		segments[i].myLine.a= m;
		segments[i].myLine.b= -1;
		segments[i].myLine.c= p1.y- m*p1.x;
		segments[i].myLine.m= m;
		segments[i].myLine.dir= dir;	

		myfile << p1.x << "\t" << p1.y << "\t" << dp.x << "\t" << dp.y << "\n" ;

	}
	myfile << "\n\n#Intersections";
	//We go to calculate all intersection
	for(i=0;i<NUM_LINES-1;i++){
		segm s1=segments[i];
		for(int j=i+1; j<NUM_LINES;j++){
			segm s2=segments[j];
			vec2f result;
			calculateIntersection(s1,s2,&result);
			myfile << result.x << "\t" << result.y << "\n" ;
		}
	}

	myfile.close();	

	FILE *pg = popen("/usr/local/bin/gnuplot", "w");
	if(!pg)
	{
		cerr << "popen failed: " << strerror(errno) << '\n';
		return 1;
	}
	fputs("plot  \"/tmp/test_001.data\" index 1 title \"Points\" with vectors, \"/tmp/test_001.data\" index 2 title \"Intersections\", \"/tmp/test_001.data\" index 0 title \"Vanishing point\"  \n", pg);
	fflush(pg);
	sleep(3);
	cin.get();
	pclose(pg);
}

